package dyy.zc.computergradeexam.ui.activity;

import android.app.ProgressDialog;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import dyy.zc.computergradeexam.R;
import dyy.zc.computergradeexam.base.BaseActivity;
import dyy.zc.computergradeexam.bean.BianChengInfo;
import dyy.zc.computergradeexam.bean.ChooseInfo;
import dyy.zc.computergradeexam.bean.TianKong;
import dyy.zc.computergradeexam.utils.BmobUtils;
import dyy.zc.computergradeexam.utils.ToastUtils;
import dyy.zc.computergradeexam.views.MyAlertDialog;

public class ExamActivity extends BaseActivity implements View.OnClickListener {

    private TextView title,timeClock,right,tijiao;
    private Timer timer;
    private int min = 45;
    private int sec = 0;
    private TextView type,question;
    private TextView question_tiankong;
    private TextView[] answer = new TextView[4];
    private int[] answerIDs = {R.id.xuanze_A,R.id.xuanze_B,R.id.xuanze_C,R.id.xuanze_D};
    private boolean[] choose = { false , false , false , false };
    private LinearLayout xuanze,tiankong;

    private BmobUtils bmobUtils;
    private final int CHOOSE_SUCCESS = 2;
    private final int TIANKONG_SUCCESS = 3;
    private final int BIANCHENG_SUCCESS = 4;
    private final int SUCCESS = 5;
    private boolean tick = true;
   private boolean getChoose = false;
   private boolean getTian = false;
   private boolean getBian = false;
    private int count=0;//标记第几题
    private int typeQuestion;//题目类型
    private int correctAnswer = -1;//标记正确答案是第几个
    private List<ChooseInfo> chooseInfoList = new ArrayList<>();
    private List<TianKong> tianKongList = new ArrayList<>();
    private List<BianChengInfo> bianChengList = new ArrayList<>();
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1://计时
                    if ((min <= 0)&&(sec <=0)){
                        timer.cancel();
                        timeClock.setText(min+"分"+sec+"秒");
                        ToastUtils.shortToast(ExamActivity.this,"考试时间到！！！");

                    }else {
                        timeClock.setText(min+"分"+sec+"秒");

                    }
                    break;
                case CHOOSE_SUCCESS:
                    getChoose = true;
                    handler.sendEmptyMessage(SUCCESS);
                    break;
                case TIANKONG_SUCCESS:
                    getTian = true;
                    handler.sendEmptyMessage(SUCCESS);
                    break;
                case BIANCHENG_SUCCESS:
                    getBian = true;
                    handler.sendEmptyMessage(SUCCESS);
                    break;
                case SUCCESS:
                    if (getChoose&&getBian&&getTian){
                        setQuestion(1);
                        dialog.dismiss();
                        timer = new Timer();
                        timer.schedule(timerTask,1000,1000);
                    }
                    break;
                case 123://切换填空题
                    count = 0;
                    typeQuestion = 2;
                    type.setText("填空题");
                    xuanze.setVisibility(View.GONE);
                    tiankong.setVisibility(View.VISIBLE);
                    setQuestion(typeQuestion);
                    break;
                case 234://切换成编程题
                    count = 0;
                    typeQuestion = 3;
                    type.setText("编程题");
                    setQuestion(typeQuestion);
                    break;
            }
        }
    };

    /**
     * 设置题目
     */
    private void setQuestion(int type) {
        switch (type){
            case 1://选择题
                ChooseInfo chooseInfo = chooseInfoList.get(count);
                question.setText((count+1)+"、"+chooseInfo.getQuestion());
                answer[0].setText(chooseInfo.getAnswerA());
                answer[1].setText(chooseInfo.getAnswerB());
                answer[2].setText(chooseInfo.getAnswerC());
                answer[3].setText(chooseInfo.getAnswerD());
                correctAnswer = getCorrectAnswer(chooseInfo.getAnswer().split("：")[1]);
                choose[correctAnswer] = true;
                break;
            case 2://填空题
                TianKong tianKong = tianKongList.get(count);
                question_tiankong.setText((chooseInfoList.size()+count+1)+"、"+tianKong.getQuestion());
                break;
            case 3://编程题
                BianChengInfo bianChengInfo = bianChengList.get(count);
                question_tiankong.setText((chooseInfoList.size()+tianKongList.size()+count+1)+"、"+bianChengInfo.getQueation());
                break;
        }
        tick  = true;
    }

    /**
     * 解析正确选项
     * @param s
     * @return
     */
    public int getCorrectAnswer(String s){
        int i = 0;
        switch (s){
            case "A":i = 0;break;
            case "B":i = 1;break;
            case "C":i = 2;break;
            case "D":i = 3;break;
        }
        return i;
    }

    @Override
    protected void findViewByIDS() {
        title = findViewsById(R.id.top_tv_title);
        right = findViewsById(R.id.top_tv_right);
        timeClock = findViewsById(R.id.timeClock);
        type = findViewsById(R.id.type);
        for (int i = 0;i<4;i++){
            answer[i] = findViewsById(answerIDs[i]);
        }
        question = findViewsById(R.id.xuanze_name);
        question_tiankong = findViewsById(R.id.tiannkong_name);
        xuanze = findViewsById(R.id.xuanze_ll);
        tiankong = findViewsById(R.id.tiankong_ll);
        tijiao = findViewsById(R.id.tijiao);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exam);
        initData();
        bind();
    }

    private void bind() {
        tijiao.setOnClickListener(this);
        findViewsById(R.id.top_rl_right).setOnClickListener(this);
        for (int i = 0;i<4;i++){
            answer[i].setOnClickListener(selectListener);
        }
    }

    private View.OnClickListener selectListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (tick) {
                for (int i = 0; i < 4; i++) {
                    if (v.getId() == answerIDs[i]) {
                        check(i);
                    }
                }
            }
        }
    };



    /**
     * 检查题目选项
     * @param i
     */
    private void check(int i) {
        tick = false;
        resetImg();
        if (choose[i]) {//判断是否选择的是正确答案
            answer[i].setTextColor(getResources().getColor(R.color.colorWhite));
            answer[i].setBackgroundColor(getResources().getColor(R.color.colorBlue));
        }else {
            answer[i].setTextColor(getResources().getColor(R.color.colorWhite));
            answer[i].setBackgroundColor(getResources().getColor(R.color.colorRed));
            answer[correctAnswer].setTextColor(getResources().getColor(R.color.colorWhite));
            answer[correctAnswer].setBackgroundColor(getResources().getColor(R.color.colorBlue));

        }
    }

    /**
     * 重置颜色
     */
    private void resetImg() {
        for(int i = 0;i<4;i++){

            answer[i].setTextColor(getResources().getColor(R.color.colorBlack));
            answer[i].setBackgroundColor(getResources().getColor(R.color.colorWhite));
        }
    }

    private void initData() {
        bmobUtils = new BmobUtils(this);
        title.setText("考试中");
       right.setText("下一题");
        right.setVisibility(View.VISIBLE);
        typeQuestion = 1;
        dialog = ProgressDialog.show(this,null,"正在生成试卷");
        bmobUtils.getChooseExam(chooseInfoList,CHOOSE_SUCCESS,handler);
        bmobUtils.getTianKongExam(tianKongList,TIANKONG_SUCCESS,handler);
        bmobUtils.getBianExam(bianChengList,BIANCHENG_SUCCESS,handler);
    }

    /**
     *  结束考试---提前结束考试
     */
    public void finishPreExam(){
        MyAlertDialog logDialog = new MyAlertDialog(this);
        logDialog.builder()
                .setTitle("退出提示")
                .setMsg("题目还没有做完呢")
                .setNegativeButton("火大不做了", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        saveWrong();
                        timer.cancel();
                        finish();
                    }
                })
                .setPositiveButton("开个玩笑", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                })
                .show();
    }

    /**
     *  结束考试---时间到结束考试
     */
    public void timeFinish(){
        MyAlertDialog logDialog = new MyAlertDialog(this);
        logDialog.builder()
                .setTitle("交卷提示")
                .setMsg("考试时间到！！！")
                .setNegativeButton("不交也得交", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        saveWrong();
//                        timer.cancel();
                        finish();
                    }
                })
                .setPositiveButton("交卷", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                })
                .show();
    }

    @Override
    public void backClick(View view) {
        finishPreExam();
    }

    // 捕获返回键的方法1
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        && event.getRepeatCount() == 0
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                // 按下BACK，同时没有重复
                finishPreExam();
            }
        return super.onKeyDown(keyCode, event);
    }

    /**
     *  结束考试---正常结束
     */
    public void finishExam(){
        MyAlertDialog logDialog = new MyAlertDialog(this);
        logDialog.builder()
                .setTitle("提示")
                .setMsg("确定交卷么？")
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        saveWrong();
                    }
                })
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        timer.cancel();
                        finish();
                    }
                })
                .show();
    }

    /**
     * 倒计时
     */
    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            sec--;
            if (sec == 0){
                handler.sendEmptyMessage(1);
            }else {
                if (sec <= 0){
                    sec = 59;
                    min--;
                }
                handler.sendEmptyMessage(1);
            }

        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_rl_right://下一题
                resetImg();
                count++;
                switch (typeQuestion){
                    case 1:
                        if (count<chooseInfoList.size()){
                            setQuestion(typeQuestion);
                            for (int i = 0;i<4;i++){
                                choose[i] = false;
                            }
                        }else {
                            handler.sendEmptyMessage(123);
                        }
                        break;
                    case 2:
                        if (count < tianKongList.size()){
                            setQuestion(typeQuestion);
                        }else {
                            handler.sendEmptyMessage(234);
                        }
                        break;
                    case 3:
                        if (count==bianChengList.size()-1){
                            tijiao.setVisibility(View.VISIBLE);
                        }
                        if (count < bianChengList.size()){
                            setQuestion(typeQuestion);
                        }else {
                            ToastUtils.shortToast(ExamActivity.this,"这已经是最后一题啦");
                        }
                        break;
                }
                break;
            case R.id.tijiao:finishExam();break;
        }
    }
}
